import dayjs = require('dayjs');
import * as events from 'events';
/**
 * Random string function.
 * Remove I,1,L;O0;
 * @param length Random string length.
 */
export function getRandomString(length: number) {
  let charSet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
  let maxPos = charSet.length;
  let code = '';
  for (let i = 0; i < length; i++) {
    code += charSet.charAt(Math.floor(Math.random() * maxPos));
  }
  return code;
}

// Global event emitter.
export const emitter = new events.EventEmitter();

/**
 * @param data [ { birthday: '1990-01-01' }, {}, {} ]
 * @param params { birthday: "date" }
 * @returns 
 */
export const dealwithMySQLDate = (data: any, params: Object) => {
  const date = "YYYY-MM-DD";
  const datetime = "YYYY-MM-DD HH:mm:ss";
  return data?.map((i: Object) => {
    Object.entries(i).forEach(([key, value]) => {
      const type = params[key];
      if (type === "date" && value) {
        i[key] = dayjs(value).format(date);
      } else if (type === "datetime" && value) {
        i[key] = dayjs(value).format(datetime);
      }
    });
    return i;
  });
};
